package com.yatong.controller;

import com.yatong.entity.Company;
import com.yatong.entity.Speech;
import com.yatong.entity.SysUser;
import com.yatong.entity.TrackRecord;
import com.yatong.service.CompanyService;
import com.yatong.service.SpeechService;
import com.yatong.service.TrackRecordService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * (TrackRecord)表控制层
 *
 * @author makejava
 * @since 2018-10-31 09:01:39
 */
@Controller
@RequestMapping("trackRecord")
public class TrackRecordController {
    /**
     * 服务对象
     */
    @Autowired
    private TrackRecordService trackRecordService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SpeechService speechService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public TrackRecord selectOne(Integer id) {
        return this.trackRecordService.queryById(id);
    }

    /**
     * 访问跟单记录页
     * @param model
     * @return
     */
    @RequestMapping("/trackingLog_view")
    public String trackingLog_view(Model model, HttpServletRequest request,
                                   @RequestParam(required = false) String id ,
                                   @RequestParam(required = false) String trackstate){
        List<TrackRecord> trackRecords = this.trackRecordService.queryAll(id);
        model.addAttribute("trackRecords",trackRecords);
        model.addAttribute("trackstate",trackstate);
        model.addAttribute("companyId",id);

        //获取当前登陆人信息
        SysUser sysUser = (SysUser)SecurityUtils.getSubject().getPrincipal();
        Speech speech = new Speech();

        speech.setUserId(sysUser.getId());
        List<Speech> speeches = this.speechService.queryAll(speech);
        model.addAttribute("speeches",speeches);

        return "trackingLog/trackingLog_view";
    }


    /**
     * 保存跟单记录
     * @param model
     * @return
     */
    @RequestMapping("/trackingLog_save")
    @ResponseBody
    public TrackRecord trackingLog_save(TrackRecord trackRecord,@RequestParam(required = false) String dcTime, Model model){
//        String flag = "0";
        //更新下次跟进时间
        if (dcTime != null && dcTime != ""){
            Company company = companyService.queryById(trackRecord.getCompanyId());
            company.setIntentionalTime(dcTime);
            companyService.update(company);
        }

        //添加跟进记录
        TrackRecord insert = this.trackRecordService.insert(trackRecord);
//        if (insert != null)
//            flag = "1";
        return insert;
    }

}